package com.mf.service.impl.basic.webPage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.exception.GraceException;
import com.mf.service.basic.webPage.ServicePageItem;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.basic.webPage.DtoPageJsonConfig;
import com.mf.entity.req.basic.search.webPage.SearchReqPageJsonConfig;
import com.mf.mapper.basic.webPage.MapperPageJsonConfig;
import com.mf.service.basic.webPage.ServicePageJsonConfig;

import java.util.List;


@Service
public class ImplServicePageJsonConfig extends ServiceImpl<MapperPageJsonConfig, DtoPageJsonConfig> implements ServicePageJsonConfig {
    @Resource
    private ServicePageItem servicePageItem;
    @Resource
    private MapperPageJsonConfig mapperPageJsonConfig;

    /**
     * 参数查询条件
     */
    @Override
    public LambdaQueryWrapper<DtoPageJsonConfig> fillParams(SearchReqPageJsonConfig params) {
        LambdaQueryWrapper<DtoPageJsonConfig> wrapper = loadQw();
        wrapper.like(StringUtils.isNotBlank(params.getKey()), DtoPageJsonConfig::getCname, params.getKey())
                .eq(StringUtils.isNotBlank(params.getType()), DtoPageJsonConfig::getType, params.getType())
                .orderByDesc(DtoPageJsonConfig::getSort).orderByDesc(DtoPageJsonConfig::getId);
        return wrapper;
    }

    /**
     * 删除
     */
    @Override
    public void deleteById(Integer id) {
        GraceException.display(servicePageItem.countByJsonId(id) > 0, "当前配置已经被使用不可删除" );
        removeById(id);
    }

    /**
     * 保存
     */
    @Override
    public DtoPageJsonConfig saveConfig(DtoPageJsonConfig config) {
        final LambdaQueryWrapper<DtoPageJsonConfig> wrapper = loadQw();
        wrapper.orderByDesc(DtoPageJsonConfig::getSort)
                .last("limit 1" );
        // 获取最大排序的一条数据，把排序设置比他大10
        final List<DtoPageJsonConfig> list = list(wrapper);
        if (!list.isEmpty()) {
            config.setSort(list.get(0).getSort() + 10);
        }
        save(config);
        return config;
    }

    /**
     * 复制配置
     */
    @Override
    public void copy(Integer id) {
        DtoPageJsonConfig dtoPageJsonConfig = findCheckById(id, true);
        dtoPageJsonConfig.setId(null);
        dtoPageJsonConfig.setCname(dtoPageJsonConfig.getCname() + "copy-" + System.currentTimeMillis());
        saveConfig(dtoPageJsonConfig);
    }
}